package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.CategoryDTO;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Employee;
import com.sky.mapper.CategoryMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.CategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CategoryServicelmpl implements  CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    //根据类型查询分类
    public List<Category> list(Integer type) {
        return categoryMapper.list(type);
    }

    //分类分页查询
    @Override
    public PageResult page(CategoryPageQueryDTO categoryPageQueryDTO) {
        PageHelper.startPage(categoryPageQueryDTO.getPage(),categoryPageQueryDTO.getPageSize());
        Page<Category> page=categoryMapper.pageQuery(categoryPageQueryDTO);
        long total = page.getTotal();
        List<Category> result = page.getResult();
        return new PageResult(total,result);
    }

    //启用禁用分类
    @Override
    public void startOrStop(Integer status, Long id) {
        Category category = Category.builder()
                        .id(id)
                .status(status).
                build();

        categoryMapper.update(category);
    }

    @Override
    public void save(CategoryDTO categoryDTO) {
        Category category=new Category();
        //BeanUtils是spb的类 这个方法是对象属性拷贝  把第一个对象的属性拷贝到第二个对象 两对象属性名要一致
        BeanUtils.copyProperties(categoryDTO,category);

        //设置状态 1为正常 ENABLE   0异常 DISABLE  初始分类应设置禁用 否则客户端出现新分类无菜品情况
        category.setStatus(StatusConstant.DISABLE);

        //设置创建和更新修改时间  !!
        //category.setCreateTime(LocalDateTime.now());
        //category.setUpdateTime(LocalDateTime.now());

        //设置记录创建人id和修改人id  ThreadLocal获取id  只能线程内访问
        //category.setCreateUser(BaseContext.getCurrentId());
        //category.setUpdateUser(BaseContext.getCurrentId());
        categoryMapper.insert(category);
    }

    //修改分类
    @Override
    public void update(CategoryDTO categoryDTO) {
        //mapping的update要传employee类型  进行转换
        Category category=new Category();
        BeanUtils.copyProperties(categoryDTO, category);

        categoryMapper.update(category);
    }

    //根据id删除分类
    @Override
    public void deleteByid(Long id) {
        categoryMapper.deleteByid(id);
    }
}
